<template>
  <!-- 主要内容 -->
  <div class="container-fluid p-4">
    <!-- 日志概览 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">日志概览</h5>
              <div>
                <el-select v-model="overviewTimeRange" placeholder="选择时间范围" size="small" style="width: 150px">
                  <el-option label="今日" value="today"></el-option>
                  <el-option label="本周" value="week"></el-option>
                  <el-option label="本月" value="month"></el-option>
                  <el-option label="本年" value="year"></el-option>
                </el-select>
              </div>
            </div>
          </template>

          <el-row :gutter="20" class="mb-4">
            <el-col :span="6">
              <el-card shadow="hover" class="statistic-card">
                <div class="d-flex align-items-center">
                  <div class="flex-shrink-0">
                    <div class="bg-primary bg-gradient text-white rounded-circle p-3">
                      <i class="bi bi-activity"></i>
                    </div>
                  </div>
                  <div class="flex-grow-1 ms-3">
                    <h6 class="mb-1 text-muted">总操作次数</h6>
                    <h4 class="mb-0">{{ overviewStats.totalCount || 0 }}</h4>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="statistic-card">
                <div class="d-flex align-items-center">
                  <div class="flex-shrink-0">
                    <div class="bg-success bg-gradient text-white rounded-circle p-3">
                      <i class="bi bi-person-check"></i>
                    </div>
                  </div>
                  <div class="flex-grow-1 ms-3">
                    <h6 class="mb-1 text-muted">活跃用户数</h6>
                    <!-- <h4 class="mb-0">256</h4> -->
                    <h4 class="mb-0">{{ activeUsers }}</h4>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="statistic-card">
                <div class="d-flex align-items-center">
                  <div class="flex-shrink-0">
                    <div class="bg-warning bg-gradient text-white rounded-circle p-3">
                      <i class="bi bi-exclamation-triangle"></i>
                    </div>
                  </div>
                  <div class="flex-grow-1 ms-3">
                    <h6 class="mb-1 text-muted">异常操作</h6>
                    <h4 class="mb-0">{{ overviewStats.errorCount || 0 }}</h4>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="statistic-card">
                <div class="d-flex align-items-center">
                  <div class="flex-shrink-0">
                    <div class="bg-info bg-gradient text-white rounded-circle p-3">
                      <i class="bi bi-clock-history"></i>
                    </div>
                  </div>
                  <div class="flex-grow-1 ms-3">
                    <h6 class="mb-1 text-muted">平均响应时间</h6>
                    <h4 class="mb-0">{{ overviewStats.avgResponseTime || 0 }}ms</h4>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-container" id="operation-trend-chart"></div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container" id="operation-type-chart"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志查询 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h5 class="mb-0">日志查询</h5>
            </div>
          </template>
          <el-form :model="logFilterForm" label-position="top" @submit.prevent="searchLogs">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="用户ID">
                  <el-input v-model="logFilterForm.userId" placeholder="输入用户ID" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="操作类型">
                  <el-input v-model="logFilterForm.paramsSummary" placeholder="输入操作类型" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="时间范围">
                  <el-date-picker v-model="logFilterForm.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                    @change="handleDateChange"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="&nbsp;">
                  <el-button type="primary" @click="searchLogs" class="w-100" :loading="loading">
                    <i class="bi bi-search me-2"></i>查询
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-select v-model="logFilterForm.status" placeholder="全部状态" clearable>
                    <el-option label="成功" :value="1"></el-option>
                    <el-option label="失败" :value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="IP地址">
                  <el-input v-model="logFilterForm.ipAddress" placeholder="输入IP地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="关键词">
                  <el-input v-model="logFilterForm.keyword" placeholder="输入操作内容关键词">
                    <template #append>
                      <el-button @click="clearLogFilters">
                        <i class="bi bi-x-circle"></i> 清空筛选
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志列表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h5 class="mb-0">操作日志列表</h5>
              <div>
                <el-button @click="refreshLogs" :loading="loading">
                  <i class="bi bi-arrow-clockwise me-2"></i>刷新
                </el-button>
              </div>
            </div>
          </template>

          <el-table :data="logList" v-loading="loading" stripe style="width: 100%"
            :default-sort="{ prop: 'operationTime', order: 'descending' }">
            <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
            <el-table-column prop="traceId" label="追踪ID" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="userId" label="用户ID" width="100" sortable></el-table-column>
            <!-- <el-table-column prop="status" label="操作类型" width="120" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="status" label="操作类型" width="120" show-overflow-tooltip>
              <template #default="{ row }">
                <span>{{ row.status === 1 ? '正常操作' : '异常操作' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="operationTime" label="操作时间" width="180" sortable>
              <template #default="scope">
                {{ formatDateTime(scope.row.operationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="ipAddress" label="IP地址" width="140"></el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? "成功" : "失败" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="responseTime" label="响应时间(ms)" width="120" sortable></el-table-column>
            <el-table-column prop="paramsSummary" label="参数摘要" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button type="text" size="small" @click="viewLogDetail(scope.row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
              :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <el-dialog v-model="logDetailVisible" title="日志完整详情" width="60%">
    <el-form v-if="selectedLogDetail" :model="selectedLogDetail" label-position="right" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="ID:">
            <el-input :value="selectedLogDetail.id" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="追踪ID (TraceId):">
            <el-input :value="selectedLogDetail.traceId" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="父追踪ID:">
        <el-input :value="selectedLogDetail.parentTraceId || '无'" readonly />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户ID:">
            <el-input :value="selectedLogDetail.userId" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建者ID:">
            <el-input :value="selectedLogDetail.creatorId" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权限ID:">
            <el-input :value="selectedLogDetail.permissionId" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源ID:">
            <el-input :value="selectedLogDetail.resourceId" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="操作时间:">
        <el-input :value="formatDateTime(selectedLogDetail.operationTime)" readonly />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="IP地址:">
            <el-input :value="selectedLogDetail.ipAddress" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态:">
            <el-tag :type="selectedLogDetail.status === 1 ? 'success' : 'danger'">
              {{ selectedLogDetail.status === 1 ? "成功" : "失败" }}
            </el-tag>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="响应时间(ms):">
            <el-input :value="selectedLogDetail.responseTime" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源类型:">
            <el-input :value="selectedLogDetail.resourceType" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="参数摘要:">
        <el-input type="textarea" :rows="4" :value="selectedLogDetail.paramsSummary" readonly />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="logDetailVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  computed,
  watchEffect,
} from "vue";
import * as echarts from "echarts";
import { useLogService } from "@/stores/logService.js";
import { useUserStore } from "@/stores/user.js"; // <-- 新增此行
import common_util from "@/util/common_util.js";
const logService = useLogService();
const userStore = useUserStore(); // <-- 新增此行
const getFormattedDate = (type) => {
  const today = new Date();
  let result;
  switch (type) {
    case "today":
      result = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
      break;
    case "oneWeekAgo":
      today.setDate(today.getDate() - 7);
      result = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
      break;
    case "oneMonthAgo":
      today.setMonth(today.getMonth() - 1);
      result = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
      break;
    case "lastYear":
      today.setFullYear(today.getFullYear() - 1);
      result = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
      break;
    default:
      result = "";
  }
  return result;
};

const overviewTimeRange = ref("week");
const logDetailVisible = ref(false); // 用于控制详情弹窗的显示
const selectedLogDetail = ref(null); // 用于存放选中的日志对象
// 日志筛选表单数据
const logFilterForm = reactive({
  userId: "",
  operationType: "",
  dateRange: [],
  ipAddress: "",
  keyword: "",
  status: null,
  paramsSummary: "",
});

// 日志列表数据
const logList = ref([]);
const loading = ref(false);

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// ECharts 实例
let operationTrendChart = null;
let operationTypeChart = null;

// 获取日志列表
// const getLogList = async () => {
//   loading.value = true;
//   try {
//     const params = {
//       pageNum: pagination.current,
//       pageSize: pagination.size,
//       userId: logFilterForm.userId || null,
//       operationType: logFilterForm.operationType || null,
//       status: logFilterForm.status,
//       startTime:
//         logFilterForm.dateRange && logFilterForm.dateRange[0]
//           ? logFilterForm.dateRange[0]
//           : null,
//       endTime:
//         logFilterForm.dateRange && logFilterForm.dateRange[1]
//           ? logFilterForm.dateRange[1]
//           : null,
//     };

//     const response = await logService.queryOperationLogs(params);
//     logList.value = response.records || [];
//     pagination.total = response.total || 0;
//     pagination.current = response.current || 1;
//     pagination.size = response.size || 10;
//     overviewStats.totalCount = pagination.total; // 1. 更新总操作次数

//     // 2. 计算平均响应时间
//     if (logList.value.length > 0) {
//       const totalResponseTime = logList.value.reduce((sum, log) => sum + (log.responseTime || 0), 0);
//       overviewStats.avgResponseTime = (totalResponseTime / logList.value.length).toFixed(2);
//     } else {
//       overviewStats.avgResponseTime = 0;
//     }
//   } catch (error) {
//     console.error("获取日志列表失败:", error);
//     logList.value = [];
//     pagination.total = 0;
//   } finally {
//     loading.value = false;
//   }
// };

// 获取日志列表
const getLogList = async () => {
  loading.value = true;
  try {
    // 1. 构建基础查询参数
    const baseParams = {
      userId: logFilterForm.userId || null,
      operationType: logFilterForm.operationType || null,
      startTime:
        logFilterForm.dateRange && logFilterForm.dateRange[0]
          ? `${logFilterForm.dateRange[0]} 00:00:00`
          : null,
      endTime:
        logFilterForm.dateRange && logFilterForm.dateRange[1]
          ? `${logFilterForm.dateRange[1]} 23:59:59`
          : null,
    };

    // 2. 查询符合当前筛选条件的日志列表 (用于表格展示)
    const mainQueryParams = {
      ...baseParams,
      pageNum: pagination.current,
      pageSize: pagination.size,
      status: logFilterForm.status,
    };
    const response = await logService.queryOperationLogs(mainQueryParams);
    logList.value = response.records || [];
    pagination.total = response.total || 0;

    // 3. 【修复关键】根据筛选条件，更新概览统计
    // 如果筛选了特定状态 (成功/失败)，总数就是列表的总数
    if (logFilterForm.status !== null) {
        overviewStats.totalCount = response.total || 0;
    } else {
        // 如果未筛选状态，需要单独查询总数
        const totalCountResponse = await logService.queryOperationLogs({ ...baseParams, pageNum: 1, pageSize: 1 });
        overviewStats.totalCount = totalCountResponse.total || 0;
    }

    // 4. 【修复关键】根据筛选条件，更新异常操作数
    // 无论主查询的状态是什么，都单独查询一次 status: 0 的数量
    const errorQueryParams = { ...baseParams, status: 0, pageNum: 1, pageSize: 1 };
    const errorResponse = await logService.queryOperationLogs(errorQueryParams);
    overviewStats.errorCount = errorResponse.total || 0;


    // 5. 更新平均响应时间 (基于当前页的近似值)
    if (logList.value.length > 0) {
      const totalResponseTime = logList.value.reduce((sum, log) => sum + (log.responseTime || 0), 0);
      overviewStats.avgResponseTime = (totalResponseTime / logList.value.length).toFixed(2);
    } else {
      overviewStats.avgResponseTime = 0;
    }

  } catch (error) {
    console.error("获取日志列表失败:", error);
    logList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索日志
const searchLogs = () => {
  pagination.current = 1; // 重置到第一页
  getLogList();
};

// 刷新日志
const refreshLogs = () => {
  getLogList();
};

// 清空筛选
const clearLogFilters = () => {
  logFilterForm.userId = "";
  logFilterForm.operationType = "";
  logFilterForm.dateRange = [];
  logFilterForm.ipAddress = "";
  logFilterForm.keyword = "";
  logFilterForm.status = null;
  searchLogs();
};

// 分页处理
const handleSizeChange = (newSize) => {
  pagination.size = newSize;
  pagination.current = 1;
  getLogList();
};

const handleCurrentChange = (newCurrent) => {
  pagination.current = newCurrent;
  getLogList();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

function handleDateChange() {
  if (logFilterForm.dateRange && logFilterForm.dateRange.length === 2) {
    const [startDate, endDate] = logFilterForm.dateRange;

    // 给开始日期和结束日期添加时间部分
    logFilterForm.dateRange = [`${startDate} 00:00:00`, `${endDate} 23:59:59`];
  }
} // 查看日志详情
// 查看日志详情
const viewLogDetail = (row) => {
  selectedLogDetail.value = row; // 将点击的行数据赋值给 selectedLogDetail
  logDetailVisible.value = true;  // 设置为 true，以显示弹窗
};
// 全局统计数据
// const overviewStats = reactive({
//   totalCount: 0,
//   errorCount: 0,
//   avgResponseTime: 0,
//   activeUsers: 256 // 假设这个值是固定的或从其他地方获取
// });
const overviewStats = reactive({
  totalCount: 0,
  errorCount: 0,
  avgResponseTime: 0,
});
const activeUsers = ref(0); // <-- 新增此行，用于存放活跃用户数

// 趋势数据
const trendData = ref([]);
const loadTrendData = async () => {
  try {
    const response = await logService.getTrend(
      "DAY",
      getFormattedDate("oneWeekAgo"),
      getFormattedDate("today")
    );

    // 确保我们处理的是正确的数据格式
    // 用户提供的数据格式示例：
    // [
    //   {
    //     "cycleType": "",
    //     "operationType": "",
    //     "totalCount": 0,
    //     "errorCount": 0,
    //     "avgResponseTime": 0,
    //     "errorRate": 0
    //   }
    // ]
    const data = Array.isArray(response) ? response : (response?.data || []);

    if (data && data.length > 0) {
      console.log("Trend data received:", data);
      trendData.value = data;

      // 更新全局统计数据
      if (data.length > 0) {
        // 计算总操作次数、错误次数和平均响应时间
        overviewStats.totalCount = data.reduce((sum, item) => sum + (item.totalCount || 0), 0);
        overviewStats.errorCount = data.reduce((sum, item) => sum + (item.errorCount || 0), 0);

        // 计算平均响应时间
        const totalResponseTime = data.reduce((sum, item) => sum + (item.avgResponseTime || 0), 0);
        overviewStats.avgResponseTime = data.length > 0 ? (totalResponseTime / data.length).toFixed(2) : 0;
      }

      // 初始化趋势图
      initOperationTrendChart();
    } else {
      console.error("Trend data is invalid or empty", data);
      trendData.value = [];
    }
  } catch (error) {
    console.error("获取趋势数据失败:", error);
    trendData.value = [];
  }
};

const initOperationTrendChart = () => {
  const chartDom = document.getElementById("operation-trend-chart");
  if (!chartDom) {
    console.error("操作趋势图表DOM元素不存在");
    return;
  }

  // 如果图表实例不存在，则创建新实例
  if (!operationTrendChart) {
    operationTrendChart = echarts.init(chartDom);
  }

  // 检查数据是否有效
  if (!trendData.value || !Array.isArray(trendData.value) || trendData.value.length === 0) {
    console.error("Trend data is invalid or empty", trendData.value);
    // 显示一个空的图表或提示信息
    operationTrendChart.setOption({
      title: {
        text: "操作趋势",
        left: "center",
        subtext: "暂无数据"
      },
      tooltip: {
        trigger: "axis"
      },
      xAxis: {
        type: "category",
        data: []
      },
      yAxis: {
        type: "value"
      },
      series: []
    });
    return;
  }

  // 数据有效，提取操作次数 (totalCount)
  console.log("Setting trend chart with data:", trendData.value);
  const operationCounts = trendData.value.map(item => item.totalCount || 0);

  // 生成日期标签（最近7天）
  const dateLabels = [];
  for (let i = 6; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dateLabels.push(`${date.getMonth() + 1}/${date.getDate()}`);
  }

  // 配置图表的选项
  const option = {
    title: {
      text: "操作趋势",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: dateLabels,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "操作次数",
        type: "line",
        data: operationCounts,
      },
    ],
  };

  // 更新图表的配置项
  operationTrendChart.setOption(option);
};
// 操作类型分布数据
const typeChartData = ref([]);
const isLoading = ref(true); // 用来判断是否加载完成
// 新增：获取活跃用户数
const fetchActiveUsers = () => {
  userStore.fetchAllUsers(
    (userList) => {
      if (Array.isArray(userList)) {
        const oneWeekAgo = new Date();
        oneWeekAgo.setDate(oneWeekAgo.getDate() - 7); // 计算7天前的时间点

        const count = userList.filter(user => {
          // 确保 updatedAt 存在，再进行比较
          return user.updatedAt && new Date(user.updatedAt) > oneWeekAgo;
        }).length;
        activeUsers.value = count;
      }
    },
    (error) => {
      console.error("获取活跃用户数失败:", error);
      activeUsers.value = 0; // 如果获取失败，设置为0
    }
  );
};
// 异步获取操作类型分布数据
const loadDistributionData = async () => {
  try {
    // 使用当前日期获取分布数据
    const today = getFormattedDate("today");
    const response = await logService.getDistribution("DAY", today);

    // 确保我们处理的是正确的数据格式
    // 用户提供的数据格式示例：
    // [
    //   { 
    //     "statCycle": "DAY", 
    //     "operationType": "USER", 
    //     "totalCount": 4, 
    //     "errorCount": 0, 
    //     "avgResponseTime": 0.0, 
    //     "errorRate": 0.0, 
    //     "statDate": "2025-07-06T16:00:00.000+00:00" 
    //   }
    // ]
    const rawData = Array.isArray(response) ? response : (response?.data || []);

    // if (rawData && rawData.length > 0) {
    //   console.log("Distribution data received:", rawData);

    //   // 格式化数据用于饼图
    //   typeChartData.value = rawData.map((item) => ({
    //     value: item.totalCount || 0,
    //     name: item.operationType || "未知操作"
    //   }));

    //   // 如果全局统计数据还没有从趋势数据中获取，则从分布数据中获取
    //   if (overviewStats.totalCount === 0) {
    //     overviewStats.totalCount = rawData.reduce((sum, item) => sum + (item.totalCount || 0), 0);
    //     overviewStats.errorCount = rawData.reduce((sum, item) => sum + (item.errorCount || 0), 0);

    //     // 计算平均响应时间
    //     const validItems = rawData.filter(item => item.avgResponseTime !== undefined && item.avgResponseTime !== null);
    //     if (validItems.length > 0) {
    //       const totalResponseTime = validItems.reduce((sum, item) => sum + item.avgResponseTime, 0);
    //       overviewStats.avgResponseTime = (totalResponseTime / validItems.length).toFixed(2);
    //     }
    //   }

    //   // 初始化操作类型图表
    //   initOperationTypeChart();
    if (rawData && rawData.length > 0) {
      console.log("Distribution data received:", rawData);

      // 格式化数据用于饼图
      typeChartData.value = rawData.map((item) => ({
        value: item.totalCount || 0,
        name: item.operationType || "未知操作"
      }));

      // 初始化操作类型图表
      initOperationTypeChart();
    } else {
      typeChartData.value = [];
      console.error("Distribution data is invalid or empty", rawData);
    }
    isLoading.value = false; // 数据加载完成
  } catch (error) {
    console.error("Error fetching distribution data:", error);
    typeChartData.value = [];
    isLoading.value = false; // 数据加载完成
  }
};

// 初始化操作类型图表
const initOperationTypeChart = () => {
  const chartDom = document.getElementById("operation-type-chart");
  if (!chartDom) {
    console.error("操作类型图表DOM元素不存在");
    return;
  }

  // 如果图表实例不存在，则创建新实例
  if (!operationTypeChart) {
    operationTypeChart = echarts.init(chartDom);
  }

  // 检查数据是否有效
  if (!typeChartData.value || typeChartData.value.length === 0) {
    console.error("Type chart data is invalid or empty", typeChartData.value);
    // 显示一个空的图表或提示信息
    operationTypeChart.setOption({
      title: {
        text: "操作类型分布",
        left: "center",
        subtext: "暂无数据"
      },
      tooltip: {
        trigger: "item"
      },
      series: []
    });
    return;
  }

  // 数据有效，配置图表选项
  console.log("Setting type chart with data:", typeChartData.value);
  const option = {
    title: {
      text: "操作类型分布",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "操作类型",
        type: "pie",
        radius: "50%",
        data: typeChartData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
  operationTypeChart.setOption(option);
};

const resizeCharts = () => {
  operationTrendChart?.resize();
  operationTypeChart?.resize();
};

onMounted(async () => {
  // 页面加载时初始化
  // 先加载趋势数据和分布数据
  await Promise.all([
    loadTrendData(),
    loadDistributionData(),
    fetchActiveUsers() // <-- 新增此行
  ]);

  // 初始化加载日志列表
  getLogList();

  // 监听窗口大小变化，重置图表大小
  window.addEventListener("resize", resizeCharts);

  // 监听时间范围变化，重新加载数据
  watchEffect(() => {
    if (overviewTimeRange.value) {
      // 根据选择的时间范围重新加载数据
      const timeRangeMap = {
        today: { start: "today", end: "today" },
        week: { start: "oneWeekAgo", end: "today" },
        month: { start: "oneMonthAgo", end: "today" },
        year: { start: "lastYear", end: "today" }
      };

      const range = timeRangeMap[overviewTimeRange.value] || timeRangeMap.week;

      // 重新加载趋势数据
      logService.getStatsTrend(
        "DAY",
        getFormattedDate(range.start),
        getFormattedDate(range.end)
      ).then(response => {
        // 处理响应数据
        const data = Array.isArray(response) ? response : (response?.data || []);

        if (data && data.length > 0) {
          console.log("Trend data updated:", data);
          trendData.value = data;

          // 更新全局统计数据
          if (data.length > 0) {
            overviewStats.totalCount = data.reduce((sum, item) => sum + (item.totalCount || 0), 0);
            overviewStats.errorCount = data.reduce((sum, item) => sum + (item.errorCount || 0), 0);

            const totalResponseTime = data.reduce((sum, item) => sum + (item.avgResponseTime || 0), 0);
            overviewStats.avgResponseTime = data.length > 0 ? (totalResponseTime / data.length).toFixed(2) : 0;
          }

          // 重新初始化趋势图
          initOperationTrendChart();
        } else {
          console.error("Updated trend data is invalid or empty", data);
        }
      }).catch(error => {
        console.error("获取趋势数据失败:", error);
      });

      // 同时重新加载分布数据
      logService.getOperationTypeDistribution("DAY", getFormattedDate(range.end)).then(response => {
        // 处理响应数据
        const rawData = Array.isArray(response) ? response : (response?.data || []);

        if (rawData && rawData.length > 0) {
          console.log("Distribution data updated:", rawData);
          // 格式化数据用于饼图
          typeChartData.value = rawData.map((item) => ({
            value: item.totalCount || 0,
            name: item.operationType || "未知操作"
          }));

          // 重新初始化操作类型图表
          initOperationTypeChart();
        } else {
          console.error("Updated distribution data is invalid or empty", rawData);
        }
      }).catch(error => {
        console.error("获取分布数据失败:", error);
      });
    }
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeCharts);
  operationTrendChart?.dispose();
  operationTypeChart?.dispose();
});
</script>

<style scoped>
/* Bootstrap Icons 兼容性样式 */
@import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css");

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
  border-bottom: 1px solid var(--el-card-border-color);
  box-sizing: border-box;
}

.statistic-card .el-card__body {
  padding: 20px;
}

.statistic-card h6 {
  font-size: 0.9rem;
  color: #6c757d;
}

.statistic-card h4 {
  font-size: 1.5rem;
  font-weight: 600;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.bi {
  font-size: 1.2rem;
  vertical-align: -0.125em;
  fill: currentColor;
}

.bg-primary {
  background-color: #007bff !important;
}

.bg-success {
  background-color: #28a745 !important;
}

.bg-warning {
  background-color: #ffc107 !important;
}

.bg-info {
  background-color: #17a2b8 !important;
}

.bg-gradient {
  background-image: var(--bs-gradient) !important;
}

.text-white {
  color: #fff !important;
}

.rounded-circle {
  border-radius: 50% !important;
}

.p-3 {
  padding: 1rem !important;
}

.d-flex {
  display: flex !important;
}

.align-items-center {
  align-items: center !important;
}

.flex-shrink-0 {
  flex-shrink: 0 !important;
}

.flex-grow-1 {
  flex-grow: 1 !important;
}

.ms-3 {
  margin-left: 1rem !important;
}

.mb-1 {
  margin-bottom: 0.25rem !important;
}

.mb-0 {
  margin-bottom: 0 !important;
}

.me-2 {
  margin-right: 0.5rem !important;
}

.w-100 {
  width: 100% !important;
}

.text-muted {
  color: #6c757d !important;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}
</style>
